package cn.zmit.kuxi.utils;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

public class BitmapUtils {
	/**
	 * 
	 * @param file //"/mnt/sdcard/mnt/sdcard/test.jpg"
	 * @param reqWidth
	 * @param reqHeight
	 * @return
	 */
	public static Bitmap decodeSampledBitmapFromResource(String file,
			int reqWidth, int reqHeight) {
		 final BitmapFactory.Options options = new BitmapFactory.Options(); 
		 options.inJustDecodeBounds = true;
		 BitmapFactory.decodeFile(file, options); 
		 options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 
		 options.inJustDecodeBounds = false;       
		 return BitmapFactory.decodeFile(file, options);
	}

	public static Bitmap decodeSampledBitmapFromResource(Resources res,
			int resId, int reqWidth, int reqHeight) {
		final BitmapFactory.Options options = new BitmapFactory.Options();
		// 将inJustDecodeBounds属性设置为true可以避免解析过程中的内存分配
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeResource(res, resId, options);
		options.inSampleSize = calculateInSampleSize(options, reqWidth,
				reqHeight);
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeResource(res, resId, options);
	}
	/**
	 * 为了避免OOM，解析位图之前先得到他的尺寸和类型
	 * 
	 * @param options
	 * @param reqWidth
	 * @param reqHeight
	 * @return
	 */
	public static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {
		int outHeight = options.outHeight;
		int outWidth = options.outWidth;
		int inSampleSize = 1;
		if (outHeight > reqHeight || outWidth > reqWidth) {
			int halfHeight = outHeight / 2;
			int halfWidth = outWidth / 2;
			while ((halfHeight / inSampleSize) > reqHeight
					&& (halfWidth / inSampleSize) > reqWidth) {
				inSampleSize *= 2;
			}
		}
		return inSampleSize;
	}
	public static Drawable convertFromBitmap(Bitmap bitmap)
	{
		return new BitmapDrawable(null,bitmap);
	}
}
